﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Bee.Util;
using Bee.Web;
using Bee.Data;
using System.Data;
using Bee.Models;
using Bee.Security.Controllers;
using Bee.BLL;

namespace Bee.Security.Controllers
{
    public class BeeMessageController : AuthControllerBase<BeeMessage>
    {
        public override PageResult List(BeeDataAdapter dataAdapter)
        {
            bool msgReceiveFlag = dataAdapter.TryGetValue<bool>("receiveFlag", true);
            if (msgReceiveFlag)
            {
                dataAdapter["receiver"] = CurrentUserId;
            }
            else
            {
                dataAdapter["sender"] = CurrentUserId;
            }

            return View(base.List(dataAdapter).Model);
        }

        public int UnreadCount()
        {
            int recordCount = 0;

            BeeDataAdapter data = new BeeDataAdapter();
            data.Add("receiver", CurrentUserId);
            data.Add("delflag", false);
            data.Add("readflag", false);

            using (DbSession dbSession = GetDbSession())
            {
                recordCount = dbSession.ExecuteCommand<int>(@"select count(*) from BeeMessage where receiver = @receiver and delflag = @delflag and readflag = @readflag", data).FirstOrDefault();
            }

            OnlineUserManager.Instance.TickUserId(CurrentUserId);

            return recordCount;
        }

        public PageResult ShowUnread()
        {
            ViewData.TryGetValue<bool>("unreadFlag", true, true);

            SqlCriteria sqlCriteria = new SqlCriteria();

            sqlCriteria.Equal("receiver", CurrentUserId).Equal("delflag", false);
            sqlCriteria.Equal("readflag", false);

            using (DbSession dbSession = GetDbSession())
            {
                int recordCount = 0;
                BeeMessage beeMessage = dbSession.Query<BeeMessage>(sqlCriteria, "id asc", 1, 1, ref recordCount).FirstOrDefault();

                ViewData["endFlag"] = recordCount == 1;

                ViewData.Merge(BeeDataAdapter.From(beeMessage), true);

                if (beeMessage != null && !beeMessage.ReadFlag)
                {
                    BeeDataAdapter data = new BeeDataAdapter();
                    data["readflag"] = true;
                    dbSession.Update("BeeMessage", data, sqlCriteria.Equal("id", beeMessage.Id));
                }
            }

            return View("Show");
        }

        public override PageResult Show(int id)
        {
            ViewData.RemoveEmptyOrNull();
            int nextFlagValue = ViewData.TryGetValue<int>("nextFlag", 0);
            bool currentFlag = nextFlagValue == 0;
            bool receiveFlag = ViewData.TryGetValue<bool>("receiveFlag", true);
            bool nextFlag = nextFlagValue == 1 ? true :false;
            bool unreadFlag = ViewData.TryGetValue<bool>("unreadFlag", false);

            SqlCriteria sqlCriteria = new SqlCriteria();

            sqlCriteria.Equal(receiveFlag ? "receiver" : "sender", CurrentUserId).Equal("delflag", false);

            if(unreadFlag)
            {
                sqlCriteria.Equal("readflag", false);
            }

            int recordCount = 0;
            BeeMessage beeMessage = null;
            using (DbSession dbSession = GetDbSession())
            {
                List<BeeMessage> list = null;
                if (currentFlag)
                {
                    beeMessage = dbSession.Query<BeeMessage>(SqlCriteria.New.Equal("id", id)).FirstOrDefault();
                    if (beeMessage != null && beeMessage.Receiver != CurrentUserId && beeMessage.Sender != CurrentUserId)
                    {
                        beeMessage = null;
                    }
                }
                else if (nextFlag)
                {
                    if (id > 0)
                    {
                        sqlCriteria.GreaterThanOrEqual("id", id);
                    }

                    list = dbSession.Query<BeeMessage>(sqlCriteria, "id asc", 1, 2, ref recordCount);
                }
                else
                {
                    list = dbSession.Query<BeeMessage>(sqlCriteria.LessThanOrEqual("id", id), "id desc", 1, 2, ref recordCount);
                }

                if (!currentFlag)
                {
                    if (!unreadFlag)
                    {
                        if (list.Count == 2)
                        {
                            beeMessage = list[1];
                        }
                        else if (list.Count == 1)
                        {
                            beeMessage = list[0];
                        }
                        else
                        {
                            // do nothing here.
                        }
                        ViewData["endFlag"] = list.Count != 2;
                    }
                    else
                    {
                        if (list.Count > 0)
                        {
                            beeMessage = list[0];
                        }

                        ViewData["endFlag"] = list.Count < 2;
                    }
                    
                }

                if (beeMessage != null && !beeMessage.ReadFlag && receiveFlag)
                {
                    BeeDataAdapter data = new BeeDataAdapter();
                    data["readflag"] = true;
                    dbSession.Update("BeeMessage", data, sqlCriteria.Equal("id", beeMessage.Id));
                }
            }
            

            ViewData.Merge(BeeDataAdapter.From(beeMessage), true);
            
            return View();
        }

        public PageResult Send()
        {
            int id = ViewData.TryGetValue<int>("id", 0);
            if (id > 0)
            {
                // 只是为了不让show中逻辑不执行更新已读标记。
                bool receiveFlag = ViewData.TryGetValue<bool>("receiveFlag", false, true);
                Show(id);

                ViewData["userids"] = ViewData["receiver"];
            }
            return View();
        }

        public void Save(string userIds, string content)
        {
            List<int> userList = (from item in userIds.Split(',')
                                  select int.Parse(item)).ToList();

            using (DbSession dbSession = GetDbSession(true))
            {
                foreach (int item in userList)
                {
                    BeeMessage beeMessage = new BeeMessage();
                    beeMessage.Content = content;
                    beeMessage.Sender = CurrentUserId;
                    beeMessage.Receiver = item;
                    beeMessage.SendTime = DateTime.Now;
                    beeMessage.MessageType = 2;

                    dbSession.Save(beeMessage);
                }
                dbSession.CommitTransaction();
            }
        }
    }

}
